package com.acwer.oa.web.utils;

import java.util.Base64;
import java.util.Date;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

public class JwtUtils {

    public final static String JWT_KEY = "pansir1025";


    //1-创建JWT
    public static String createJWT(String id, String subject,String roles, Long ttlMillis){
        Date now = new Date();
        Date expireDate = new Date(now.getTime()+ttlMillis);
        SecretKey secretKey = generateKey();
        JwtBuilder jwtBuilder = Jwts.builder()
                .setHeaderParam("typ", "JWT")//
                .setId(id)
                .setSubject(subject)
                .setIssuer("tangyujie")
                .setIssuedAt(now)
                .setExpiration(expireDate)
                .signWith(SignatureAlgorithm.HS256, secretKey).claim("roles", roles);

        //jwtBuilder.compact() = base64UrlEncodedHeader + '.' + base64UrlEncodedBody + '.' + base64UrlSignature;
        return jwtBuilder.compact();
    }


    //生成key
    private static SecretKey generateKey(){
        byte[] encodeKey = Base64.getDecoder().decode(JWT_KEY);
        return new SecretKeySpec(encodeKey,0,encodeKey.length,"AES");
    }

    //获取token中注册信息
    public static Claims getTokenClaim(String token){
        SecretKey secretKey = generateKey();
        try {
            return Jwts.parser()
                    .setSigningKey(secretKey)
                    .parseClaimsJws(token)
                    .getBody();
        } catch (Exception e) {
            return null;
        }
    }

    //验证token是否过期
    public static boolean isTokenExpired(Date expirationTime){
        return expirationTime.before(new Date());
    }
}
